<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1, shrink-to-fit=no"
    />
    <title>ChatTTS WebUI & API - v{{version}}</title>
    <link href="/static/js/bootstrap.min.css" rel="stylesheet" />

    <style>
      #upload-btn {
        position: relative;
      }

      #file-input {
        position: absolute;
        left: 0;
        right: 0;
        top: 0;
        bottom: 0;
        width: 100%;
        height: 100%;
        z-index: 1;
        opacity: 0;
        cursor: pointer;
        font-size: 0;
      }

      #text-input {
        height: 88px;
        color: #3b3e55;
        font-size: 14px;
      }

      #text-input::placeholder {
        color: #9c9db4;
      }

      .btn-warning {
        background-color: #ffc107;
        border-color: #ffc107;
      }

      .font12 {
        font-size: 12px;
      }

      .w-50px {
        display: inline-block;
        width: 50px;
        white-space: nowrap;
        overflow: visible;
      }

      #submit-btn {
        color: #fff;
        font-size: 14px;
        font-style: normal;
        font-weight: 300;
        line-height: 22px;
        display: flex;
        height: 32px;
        padding: 4px 16px;
        justify-content: center;
        align-items: center;
        gap: 10px;
        border-radius: 4px;
        background: #000;
        border: none;
        /* margin: 0 auto; */
        margin-top: 16px;
      }
      #my-2 {
        /* margin-top: 32px !important; */
        margin-bottom: 16px !important;
      }
      .class-layer-custom .layui-layer-btn a {
        border-color: #000;
        background-color: #000;
        font-size: 14px;
      }
      .mg-l_20 {
        margin-left: 20px !important;
      }
      .custom-text,
      .form-check-label {
        color: #3b3e55;
        font-size: 14px;
      }
      .z-index--9999 {
        z-index: -9999;
      }

      #voice {
        /* height: 94px; */
        overflow: scroll;
      }

      .custom-container {
        overflow: hidden;
      }

      .mg-t_8 {
        margin-top: 8px !important;
      }

      /* @media (min-width: 1536px) {
        .custom-container {
          margin: 0 192px;
        }
      }

      @media (max-width: 1535px) and (min-width: 768px) {
        .custom-container {
          margin: 0 32px;
        }
      }

      @media (max-width: 768px) {
        .custom-container {
          margin: 0 16px;
        }
      } */
    </style>
  </head>

  <body>
    <div class="custom-container px-0">
      <div class="row justify-content-center">
        <div id="my-2" class="col-12">
          <textarea id="text-input" class="form-control d-block" rows="3">
高考加油！高考必中！</textarea
          >
          <!-- <span class="text-secondary fs-6">除文本框必填外，其他均为可选，若不懂无需填写</span> -->
        </div>
        <div class="col-12">
          <div class="row align-items-center gx-1">
            <div class="col align-items-center input-group">
              <span class="custom-text">选择音色</span>
              <div class="form-check mg-l_20">
                <input
                  class="form-check-input"
                  type="radio"
                  name="voice"
                  id="flexRadioDefault1"
                  value="13"
                  checked
                />
                <label class="form-check-label" for="flexRadioDefault1">
                  女声
                </label>
              </div>
              <div class="form-check mg-l_20">
                <input
                  class="form-check-input"
                  type="radio"
                  name="voice"
                  id="flexRadioDefault2"
                  value="11"
                />
                <label class="form-check-label" for="flexRadioDefault2">
                  男声
                </label>
              </div>
              <!-- <select id="voice" class="form-control">
                <option value="11">男(11)</option>
                <option value="12">男(12)</option>
                <option value="16">男(16)</option>
                <option value="2222">男(2222)</option>
                <option value="4444">男(4444)</option>
                <option value="6653">男(6653)</option>
                <option value="7869">男(7869)</option>
                <option value="9999">男(9999)</option>
                <option value="5">女(5)</option>
                <option value="13" selected>女(13)</option>
                <option value="14">女(14)</option>
                <option value="1111">女(1111)</option>
                <option value="3333">女(3333)</option>
                <option value="4099">女(4099)</option>
                <option value="5099">女(5099)</option>
                <option value="5555">女(5555)</option>
                <option value="8888">8888</option>
                <option value="6666">6666</option>
                <option value="7777">7777</option>
              </select> -->
            </div>
          </div>
        </div>
        <div class="col-12 text-center">
          <button id="submit-btn">立即合成声音</button>
        </div>
        <div class="col-12 mg-t_8">
          <div class="row" id="audio-container"></div>
          <div class="m-2 bg-black text-white d-none" id="code"></div>
        </div>
      </div>
    </div>

    <script src="/static/js/jquery.min.js"></script>
    <script src="/static/js/layer/layer.js"></script>
    <script src="/static/js/bootstrap.bundle.min.js"></script>
    <script>
      $(document).ready(function () {
        $('[data-toggle="tooltip"]').tooltip();

        let audioGenerated = false;

        $('#temper_wrap input[type="range"]').on("input", function () {
          $(this).next().text($(this).val());
        });
        $("#submit-btn").click(function () {
          // 向父页面发送消息
          const customMessage = {
            type: "chattts",
          };
          window.parent.postMessage(JSON.stringify(customMessage), "*");

          var text = $("#text-input").val().trim();
          if (text === "") {
            layer.alert("必须输入文本", {
              title: false,
              skin: "class-layer-custom",
            });
          } else {
            let index = layer.load();
            let custom_voice = $("#custom_voice").val();
            /*
		text_list=text.split("\n").map(it=>{
			it=it.trim()
			if(it.length>150 && /。/.test(it)){
				return it.replace(/。/g,"。\n")
			}
			return it    
		});
		text=text_list.join("")
		*/
            // let data = {
            // 	text: text,
            // 	prompt: $("#prompt").val(),
            // 	voice: parseInt($("#voice").val()),
            // 	speed: parseInt($("#speed").val()),
            // 	temperature: parseFloat($("#temperature").val()),
            // 	top_p: parseFloat($("#top_p").val()),
            // 	top_k: parseFloat($("#top_k").val()),
            // 	refine_max_new_token: parseInt($("#refine_max_new_token").val()),
            // 	infer_max_new_token: parseInt($("#infer_max_new_token").val()),
            // 	text_seed: parseInt($(text_seed).val()),
            // 	skip_refine: $("#skip_refine").prop("checked") ? 1 : 0,
            // 	is_split: $("#is_split").prop("checked") ? 1 : 0,
            // 	custom_voice: custom_voice ? parseInt(custom_voice) : 0,
            // };
            let data = {
              text: text,
              prompt: $("#prompt").val(),
              voice: parseInt($('input[name="voice"]:checked').val()),
              speed: 5,
              temperature: 0.3,
              top_p: 0.7,
              top_k: 20,
              refine_max_new_token: 384,
              infer_max_new_token: 2048,
              text_seed: 42,
              skip_refine: $("#skip_refine").prop("checked") ? 1 : 0,
              is_split: $("#is_split").prop("checked") ? 1 : 0,
              custom_voice: custom_voice ? parseInt(custom_voice) : 0,
            };
            $.ajax({
              url: "/tts",
              type: "POST",
              data: data,
              timeout: 3600000,
              success: function (response) {
                if (response.code === 0) {
                  console.log(response);
                  if (response.audio_files) {
                    response.audio_files.forEach(function (audio, index) {
                      let pos = audio.filename.lastIndexOf("/") + 1;
                      let filename = audio.filename.substr(pos);
                      let jsCode = `# API调用代码

import requests

res = requests.post('http://${location.host}/tts', data=${JSON.stringify(
                        data,
                        null,
                        2
                      )})
print(res.json())

#ok
{code:0, msg:'ok', audio_files:[{filename: ${audio.filename}, url: ${
                        audio.url
                      }}]}

#error
{code:1, msg:"error"}
`;
                      let n = $("#audio-container > div").length + 1;
                      $("#audio-container").html(`
                  <div class="col-12 mb-2 pb-2 border-bottom">
					<div class="d-flex align-items-center my-1">
						<a title="移除显示，不删除wav文件" href="javascripts:;" onclick="$(this).parent().parent().remove()" class="btn btn-close font12 me-2"></a>
						<audio controls autoplay src="${audio.url}"></audio>
					</div>
                  </div>
                `);
                    });

                    audioGenerated = true;
                  } else {
                    layer.alert("音频文件生成失败", { title: false });
                  }
                } else {
                  layer.alert(response.msg, { title: false });
                }
              },
              error: function (xhr, status, error) {
                layer.alert("发生错误: " + error, { title: false });
              },
              complete: function () {
                layer.close(index);
              },
            });
          }
        });

        $(document).on("click", ".show-js-btn", function () {
          let codeContainer = $(this).parent().next(".code-container");
          codeContainer.toggleClass("d-none");
          if (!codeContainer.hasClass("d-none")) {
            codeContainer.html(
              `<pre><code>${decodeURIComponent(
                $(this).data("js-code")
              )}</code></pre>`
            );
          }
        });

        $("#upload-btn").click(function () {
          $("#file-input").click(); // Trigger file input when upload button is clicked
        });

        $("#file-input").change(function (e) {
          var file = e.target.files[0];
          if (file) {
            var reader = new FileReader();
            reader.onload = function (e) {
              $("#text-input").val(e.target.result);
            };
            reader.readAsText(file, "UTF-8");
          }
        });

        $("#clear-btn").click(function () {
          layer.confirm(
            "是否要清除所有wav文件",
            {
              btn: ["是", "否"],
              title: false,
            },
            function () {
              layer.msg("清理中...");
              $.ajax({
                url: "/clear_wavs",
                type: "POST",
                success: function (response) {
                  if (response.code === 0) {
                    $("#audio-container").html("");
                    layer.alert("清理成功", { title: false });
                  } else {
                    layer.alert("清理失败: " + response.msg, { title: false });
                  }
                },
                error: function (xhr, status, error) {
                  layer.alert("发生错误: " + error, { title: false });
                },
              });
            }
          );
        });
      });
    </script>
  </body>
</html>
